package com.ecomm.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.apache.commons.logging.Log;

import java.io.IOException;
import java.util.Properties;
import java.util.Enumeration;
import java.sql.Connection;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: Gavin
 * Date: 2007-1-30
 * Time: 21:35:15
 * To change this template use File | Settings | File Templates.
 */
public class HibernateUtil {
    private static final Log log = Logger.getLog(HibernateUtil.class);

    private static SessionFactory sessionFactory;

//    static {
//        try {
//            ClassPathResource cfg = new ClassPathResource("config/hibernate.cfg.xml");
//            ClassPathResource cfg2 = new ClassPathResource("config/hibernate.properties");
//            ClassPathResource cfg3 = new ClassPathResource("config/connection.properties");
//            Properties hibernateProps = new Properties();
//            hibernateProps.load(cfg2.getInputStream());
//            Properties connectionProps = new Properties();
//            connectionProps.load(cfg3.getInputStream());
//            Enumeration enumeration = connectionProps.keys();
//            while(enumeration.hasMoreElements()){
//                String key = (String)enumeration.nextElement();
//                hibernateProps.put("hibernate."+key,connectionProps.getProperty(key));
//            }
//            Configuration config = new AnnotationConfiguration().configure(cfg.getFile()).addProperties(hibernateProps);
//            sessionFactory = config.buildSessionFactory();
//
//        } catch(IOException excp){
//            throw new RuntimeException("Configuration problem: " + excp.getMessage(), excp);
//        }
//
//    }

    static{
        LocalSessionFactoryBean obj = (LocalSessionFactoryBean)SpringUtil.getBean("&sessionFactory");
        try{
            Method build = obj.getClass().getDeclaredMethod("buildSessionFactory");
            boolean isAccess = build.isAccessible();
            if(!isAccess){
                build.setAccessible(true);
            }
            sessionFactory = (SessionFactory)build.invoke(obj);
            build.setAccessible(isAccess);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }


//    /**
//     * 使用 spring 的dataSource.getConnection() 构建 session （注意必须自己关闭 Connection）

//     * @return
//     * @throws HibernateException
//     */
//    public static Session currentSessionWithSpringDataSource() throws HibernateException {
//        Session s = (Session) session.get();
//        // Open a new Session, if this Thread has none yet
//        if (s == null) {
//            Connection conn = null;
//            try{
//                conn = SpringUtil.getConnection();
//            }
//            catch(Exception e){
//                throw new HibernateException("error when get connection from spring",e);
//            }
//            s = sessionFactory.openSession(conn);
//            session.set(s);
//        }
//        return s;
//    }

    /**
     * 传入Connection 构建 session （注意必须自己关闭 Connection）
     * @param conn
     * @return
     * @throws HibernateException
     */
    public static Session currentSessionWithConnection(Connection conn) throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession(conn);
            session.set(s);
        }
        return s;
    }
    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
}
